﻿using RockBus.Configuration.Interfaces;
using RockBus.PipelineComponent.Interfaces;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace RockBus.Pipeline
{
    public class PipelineComponentConfiguration : IPipelineComponentConfiguration
    {
        public PipelineComponentConfiguration(string id, bool active, string soapActionFilter, IEnumerable<KeyValuePair<string, string>> configuration, IReadOnlyConfiguration readOnlyConfiguration)
        {
            this.Id = id;
            this.Active = active;
            this.SoapActionFilter = soapActionFilter;

            if (configuration != null)
            {
                this.Configuration = new Dictionary<string, string>();
                foreach (var kvp in configuration)
                {
                    this.Configuration.Add(kvp.Key, kvp.Value);
                }
            }

            _soapActionRegex = new Lazy<Regex>(() =>
            {
                string pattern = "^" + Regex.Escape(this.SoapActionFilter).Replace(@"\*", ".*").Replace(@"\?", ".") + "$";
                return new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            }, true);

            this.ReadOnlyConfiguration = readOnlyConfiguration;
        }

        public string Id { get; private set; }

        public bool Active { get; private set; }

        public string SoapActionFilter { get; private set; }

        public string this[string key]
        {
            get
            {
                if ((this.Configuration != null) &&
                    this.Configuration.ContainsKey(key))
                {
                    return this.Configuration[key];
                }

                return null;
            }
        }

        public bool ShouldProcessMessage(string action)
        {
            if (!this.Active)
            {
                return false;
            }

            if (string.IsNullOrEmpty(this.SoapActionFilter))
            {
                return true;
            }

            return this.SoapActionRegex.IsMatch(action);
        }

        private readonly Lazy<Regex> _soapActionRegex;

        private Regex SoapActionRegex { get { return this._soapActionRegex.Value; } }

        private IDictionary<string, string> Configuration { get; set; }

        public IReadOnlyConfiguration ReadOnlyConfiguration { get; private set; }
    }
}